import pandas as pd

from pyecharts import Pie, Map, Style, Page, Bar
import jieba
from wordcloud import WordCloud, STOPWORDS
import matplotlib.pyplot as plt
import numpy
import PIL.Image as Image
import os
page = Page()
# 按照key得到相关list
def get_attr(friends, key):
    return list(map(lambda user:user.get(key), friends))

def get_friends():
    itchat.auto_login(hotReload=True)
    friends = itchat.get_friends(update=True)[0:]
    users = dict(province=get_attr(friends, "Province"),
                city=get_attr(friends, "City"),
                nickname=get_attr(friends, "NickName"),
                sex=get_attr(friends, "Sex"),
                signature=get_attr(friends, "Signature"),
                remarkname=get_attr(friends, "RemarkName"),
                pyquanpin=get_attr(friends, "PYQuanPin"),
                displayname=get_attr(friends, "DisplayName"),
                isowner=get_attr(friends, "IsOwner"))
    return users

def sex_stats(users):
      df = pd.DataFrame(users)
      sex_arr = df.groupby(['sex'], as_index=True)['sex'].count()
      data = dict(zip(list(sex_arr.index), list(sex_arr)))
      data['不告诉你'] = data.pop(0)
      data['帅哥'] = data.pop(1)
      data['美女'] = data.pop(2)
      return data.keys(), data.values()



def create_charts1():
    users = get_friends()
    
    style = Style(width=1100, height=600)
    style_middle = Style(width=900, height=500)
    data = sex_stats(users)
    attr, value = data
    chart = Pie('好友性别',title_color='#000')  # title_pos='center'
    chart.add('', attr, value, center=[50, 50],
            radius=[30, 70], is_label_show=True, legend_orient='horizontal', legend_pos='center',
            legend_top='bottom', is_area_show=True,is_more_utils=True)
    page.add(chart)

    a = list(attr)
    b = list(value)
    chart = Bar('数量比例',title_color='#000',  width=1200, height=600)
    chart.add('', a, b, is_stack=True, is_convert=True, label_pos='inside', is_legend_show=True,
            is_label_show=True,is_more_utils=True)
    page.add(chart)
  





def prov_stats(users):
      prv = pd.DataFrame(users)
      prv_cnt = prv.groupby('province', as_index=True)['province'].count().sort_values()
      attr = list(map(lambda x: x if x != '' else '未知', list(prv_cnt.index)))
      return attr, list(prv_cnt)  
  

def create_charts2():
    users = get_friends()
    data = prov_stats(users)
    attr, value = data
    
    chart = Map('好友全国分布',title_color='#000',  width=1200, height=600)
    chart.add('', attr, value, is_label_show=True, is_visualmap=True, visual_text_color='#000',is_more_utils=True)
    page.add(chart)
    
    chart = Bar('各省比例',title_color='#000',  width=1200, height=600)
    chart.add('', attr, value, is_stack=True, is_convert=True, label_pos='inside', is_legend_show=True,
            is_label_show=True,is_more_utils=True)
    page.add(chart)


def gd_stats(users):
    df = pd.DataFrame(users)
    data = df.query('province == "广东"')
    res = data.groupby('city', as_index=True)['city'].count().sort_values()
    attr = list(map(lambda x: '%s市' % x if x != '' else '未知', list(res.index)))
    return attr, list(res)
      
def create_charts3():
    users = get_friends()
    data = gd_stats(users)
    attr, value = data
    chart = Map('广东好友分布',title_color='#000',  width=1200, height=600)
    chart.add('', attr, value, maptype='广东', is_label_show=True, is_visualmap=True, visual_text_color='#000',is_more_utils=True)
    page.add(chart)
    chart = Bar('各市比例',title_color='#000',  width=1200, height=600)
    chart.add('', attr, value, is_stack=True, is_convert=True, label_pos='inside', is_label_show=True,is_more_utils=True)
    page.add(chart)

    






def jieba_cut(users):
      signature = users['signature']
      words = ''.join(signature)
      res_list = jieba.cut(words, cut_all=True)
      return res_list

def create_wc(words_list):
      res_path = os.path.abspath('./jieba')
      words = ' '.join(words_list)
      print(words)
      #with open(res_path+'/sign.txt','w') as f:
      #    f.write(words)
      back_pic = numpy.array(Image.open("%s/111.jpg" % res_path))
      stopwords = set(STOPWORDS)
      stopwords = stopwords.union(set(['class','span','emoji','emoji','emoji1f388','emoji1f604']))
      wc = WordCloud(background_color="white", 
                     #margin=2,
                     #width=2000,
                     #height=2000,
                     #font_path='%s/hanyiqihei.ttf' % res_path,
                     font_path='C:\Windows\Fonts\HYQiHei-25J.ttf',
                     mask=back_pic,
                     max_font_size=100,
                     stopwords=stopwords,
                     random_state=42,
                     max_words=400,
                     #scale = 1.5
                     ).generate(words)
      # image_colors = ImageColorGenerator(back_pic)
      plt.imshow(wc)
      # plt.imshow(wc.recolor(color_func=image_colors))
      plt.axis('off')
      # 绘制词云  
      #plt.figure()  
      plt.show()
      wc.to_file( res_path + '\\test.png')
      
      
     
      


#生成统计图
def run():
    create_charts1()
    create_charts2()
    create_charts3()
    page.render('微信信息.html')

#生成词云图
def fenci():
    #import itchat
    #users = get_friends()
    #words_list = jieba_cut(users)
    res_path = os.path.abspath('./jieba')

    txt = open(res_path + '/sign.txt').read()
    words = ''.join(txt)
    words_list = jieba.cut(words, cut_all=True)
    create_wc(words_list)

#run()
fenci()
print('搞定=================')